<?php
namespace app\admin\controller;

use app\common\model\User as u_table;
use app\common\model\CashUsers;
use app\common\model\Record;
use app\common\model\UserAccount;
use think\Db;
use PHPExcel_IOFactory;
use PHPExcel;
/**
 * 会员操作  赵振远
 * 2017.12.20
 * @package app\agent\controller;
 */
class User extends Base{
	/*
	*会员展示 all
	 */
    public function index(){
    	$u = new u_table();
        $map = array();
        $mobile = $this->request->param('mobile');
        if (isset($mobile)) {
            $map[] = ['mobile','like','%'.$mobile.'%'];
        }
    	$list = $u->where($map)->paginate(10, false,[
            'type'     => 'bootstrap',
            'path'     => url('User/index',['mobile'=>$mobile]),
        ]);
    	$count = $u->where($map)->count();
    	$this->assign('count',$count);
    	// 模板变量赋值
        $this->assign('list',$list);
        //模板输出
        return $this->fetch();
    }
    /**
     * 会员消费中心 订单表
     * @return [type] [description]
     */
    public function recharge(){
        $map = array();
        $nickname = $this->request->param('nickname');
        //查询搜索
        if (isset($nickname)) {
            $map[] = ['nick_name','like','%'.$nickname.'%'];
        }
        if (!empty($_POST['start_time'])) {
            $_POST['start_time'] = strtotime($_POST['start_time']);
            $map[] = ['ord_create_time', '>', $_POST['start_time']];
        }
        if (!empty($_POST['end_time'])) {
            $_POST['end_time'] = strtotime($_POST['end_time']);
            $map[] = ['ord_create_time', '<', $_POST['end_time']];
        }
        $list = Db::table('rbw_orders')
        ->where($map)
        ->alias('a')
        ->join(['rbw_shops'=>'b'],'a.ord_shop_id=b.sp_id')
        ->join(['rbw_user'=>'c'],'a.ord_user_id=c.id')
        //->select();
        ->paginate(5, false,[
            'type'     => 'bootstrap',
            'path'     => url('User/recharge',['nickname'=>$nickname]),
        ]);
        $this->assign('count',count($list));
        $this->assign('list',$list);
        return $this->fetch();
    }
    /**
     * 提现申请
     * @return [type] [description]
     */
    public function withdrawals(){
        //搜索分页
        $map = array();
        //按时间
        if (!empty($_POST['start_time'])) {
            $_POST['start_time'] = strtotime($_POST['start_time']);
            $map[] = ['cu_time', '>', $_POST['start_time']];
        }
        //按用户名搜索
        $nickname = $this->request->param('nick_name');
        if (!empty($nickname)) {
            $map[] = ['nick_name','like','%'.$nickname.'%'];
            //$map['nickname'] = array('like',$nickname);
        }
        //按用户id搜索
        $user_id = $this->request->param('user_id');
        if (!empty($user_id)) {
            $map[] = ['cu_user','=',$user_id];
        }
        //按状态搜素
        $status = $this->request->param('c_status');
        if (!empty($status)) {
            $map[] = ['cu_status','=',$status];
        }
        $list = Db::table('rbw_cash_users')
        ->where($map)
        ->alias('a')
        ->join(['rbw_user'=>'b'],'a.cu_user=b.id')
        //->select();
        ->paginate(5, false);
        $this->assign('count',count($list));
        $this->assign('list',$list);
    	return $this->fetch();
    }
    /**
     * 提现申请 更改状态
     */
    public function ajaxWith(){
            if($this->request->method() === "POST"){
                //status remark c_id
                $cash = new CashUsers;
                $u = new u_table;
                $record = new Record;
                $arr = array('status'=>'1','msg'=>'请求成功');
                $raa = array('status'=>'2','msg'=>'请求失败');
                switch($_POST['status']){
                    case 1: //前端没有直接写值 所以只去第一个下标值 并且在汇款记录中添加一条待转账的记录
                            $time = time();//审核时间 $time
                            if(isset($_POST['cu_id'][0])){
                                $id = $_POST['cu_id'][0];
                            }
                            $idd = $_POST['cu_id'][0];//从新定义id
                            if(isset($_POST['cu_id'])){
                                 $id = $_POST['cu_id'];
                            }
                            $news = $cash::get($id);//获取当前主键id信息
                            $uname = $u::get($news['cu_user']);//获取此用户
                            $u_id = $uname['id']; //此用户id
                            $money = $news['cu_money']; //当前申请金额
                            //当前账户余额
                            $u_money = Db::table('rbw_user_account')->where('ua_user', $u_id)->value('ua_account');
                            if($news['cu_status'] == 1){//判断当前状态
                                return array('status'=>'2','msg'=>'已申请通过,不可再次操作');
                            }else{
                                if($money > $u_money){//判断用户余额
                                    return array('status'=>'2','msg'=>'错误,余额不足或其他');
                                }else{
                                     //从此账户减去申请金额
                                    $sta = Db::table('rbw_user_account')->where('ua_user', $u_id)->setDec('ua_account', $money);
                                    if($sta){//如果金额扣除 则改变状态
                                        $num = $cash->save([
                                            'cu_status'  => 1
                                        ],['cu_id' => $idd]);
                                        if ($num) {//判断状态更改
                                                $req = $record->data([//最后写入汇款记录
                                                    're_uid'  =>  $news['cu_user'],
                                                    're_cid' => $news['cu_id'],
                                                    're_uname' => $uname['nick_name'],
                                                    're_cash' =>  $money,
                                                    're_audit' => $time,
                                                    're_mark' => $_POST['remark']
                                                    ])->save();
                                             if ($req) {
                                                    return json($arr);
                                             }
                                        }else{
                                            return json($raa);
                                        }
                                    }else{
                                        return array('status'=>'2','msg'=>'错误,扣款失败');
                                    }
                                }
                            }
                            break;
                    case 2: //执行申请失败操作
                            
                            if(isset($_POST['cu_id'][0])){
                                $id = $_POST['cu_id'][0];
                            }
                            $idd = $_POST['cu_id'][0];//从新定义id
                            if(isset($_POST['cu_id'])){
                                 $id = $_POST['cu_id'];
                            }
                            $news = $cash::get($id);
                            if($news['cu_status'] == 1){
                                return array('status'=>'2','msg'=>'已申请通过,不可改变');
                            }else{
                                $num = $cash->save([
                                'cu_status'  => 2
                                ],['cu_id' => $idd]);
                                if ($num) {//判断状态更改
                                    return json($arr);
                                }else{
                                    return json($raa);
                                 }
                            }
                            break;
                }
        }
    }
    /**
     * 申请详情
     * @return [type] [description]
     */
    public function with(){
        //查询 user user_account cash_with 用户 用户金额 提现记录
        $map = array();
        $cu_user = $this->request->param('id');
        if (isset($cu_user)) {
            $map[] = ['cu_user','=',$cu_user];
        }
        $uid = $this->request->param('uid');
        if (isset($uid)) {
            $map[] = ['id','=',$uid];
        }
        $res = Db::table('rbw_user')
        ->where($map)
        ->alias('a')
        ->join(['rbw_user_account'=>'w'],'a.id=w.ua_user')
        ->join(['rbw_cash_users'=>'c'],'a.id=c.cu_user')
        ->find();
        $this -> assign('res',$res);
        return $this->fetch();
    }
    /**
     * [huika  汇款 description]
     * @return [type] [description]
     */
    public function huika(){
        $record = new Record;
        $map = array();
        if ($this->request->param('state')=='1') {
            if (!empty($_POST['userid'])) {
                $map[] = ['re_uid', '=', $_POST['userid']];
            }
            if (!empty($_POST['end_time'])) {
                $_POST['end_time'] = strtotime($_POST['end_time']);
                $map[] = ['re_cashtime', '>', $_POST['end_time']];
            }
            $map[] = ['re_state','=','1'];
            $lab = $record->where($map)
            ->paginate(5, false,[
                'type'     => 'bootstrap',
                'path'     => url('User/huika'),
            ]);
            $this->assign('count',count($lab));
            $this->assign('lab',$lab);
            return $this->fetch('huikb');
        }
        if (!empty($_POST['userid'])) {
            $map[] = ['re_uid', '=', $_POST['userid']];
        }
        if (!empty($_POST['start_time'])) {
            $_POST['start_time'] = strtotime($_POST['start_time']);
            $map[] = ['re_audit', '>', $_POST['start_time']];
        }
        $map[] = ['re_state','=','-1'];
        $list = $record->where($map)
        //->select();
        ->paginate(5, false,[
            'type'     => 'bootstrap',
            'path'     => url('User/huika'),
        ]);
        $this->assign('count',count($list));
        $this->assign('list',$list);
        return $this->fetch();
    }
    /**
     * 汇款状态改变
     */
    public function hmove(){
        $id = $_POST['id'];
        $time = time();
        $rm = new Record;
        // save方法第二个参数为更新条件
        $hmove = $rm->save([
            're_state'  => '1',
            're_cashtime' => $time
        ],['re_id' => $id]);
        if ($hmove) {
            return 1;
        }else{
            return 2;
        }
    }
    /**
     * [huika  已汇款 description]
     */
    public function huikb(){
        return $this->fetch();
    }
    /*
    *单用户 详情 修改
    *
     */
    public function detail(){
    	if($this->request->method() === "POST"){
            $rnew = new u_table();
            $id = $_POST['id'];
            $rm = $rnew->save([
                'mobile'  => $_POST['mobile'],
                'static' => $_POST['static'],
                'gender' => $_POST['gender'],
            ],['id' => $id]);
            if ($rm) {
                return $this->success('修改成功',url('User/index'));
            }else{
                return $this->error();
            }
    	}else{
    		// 查询单条记录 信息
    		//$res = u_table::get($this->request->param('id'));
            $res = Db::table('rbw_user')
            ->where('id',$this->request->param('id'))
            ->alias('a')
            ->leftJoin('rbw_user_account w','a.id = w.ua_user')
            ->find();

            $num =Db::table('rbw_user')->where('parentid',$this->request->param('id'))->select();
            $this -> assign('num',count($num));
    		$this -> assign('res',$res);
    		return $this->fetch();
    	}
    }
    /*
    *执行用户冻结操作 判断当前状态
    *
     */
    public function remove(){
        if($this->request->method() === "GET"){//解除冻结
            $id = $_GET['id'];
            $rm = new u_table();
            // save方法第二个参数为更新条件
            $remove = $rm->save([
                'static'  => '1',
            ],['id' => $id]);
            if ($remove) {
                return 1;
            }else{
                return 2;
            }
        }
        //进行冻结
        $id = $_POST['id'];
        $rm = new u_table();
        // save方法第二个参数为更新条件
        $remove = $rm->save([
            'static'  => '2',
        ],['id' => $id]);
        if ($remove) {
            return 1;
        }else{
            return 2;
        }
    }
    /**
     * 会员 账户金额 明细
     */
    public function banks(){
        if($this->request->method() === "POST"){
            //$rbw_user = new u_table();
            if(!isset($_POST['nickname'])){  //如果为空则不查询name字段
                $n_name = '';
            }else{
                $n_name = '%'.$_POST['nickname'].'%';
            }
            if(!isset($_POST['mobile'])){
                $mobile = '';
            }else{
                $mobile = $_POST['mobile'];
            }
            $row = Db::table('rbw_user')
            ->where('nick_name','like',$n_name)
            ->whereOr('mobile',$mobile)
            ->alias('a')
            ->leftJoin('rbw_banks w','a.id = w.bk_user')
            ->paginate(5, false,[
            'type'     => 'bootstrap',
            'path'     => url('User/banks'),
            ]);
            //$row = $rbw_user->scope($n_name,$_POST['mobile']); //在M层方法 or
            //dump($res->getLastSql());   //查看model执行的sql
            $this->assign('count',count($row));
            $this->assign('row',$row);
            return $this->fetch();
        }
         $row = Db::table('rbw_user')
            ->alias('a')
            ->leftJoin('rbw_banks w','a.id = w.bk_user')
            ->paginate(5, false,[
            'type'     => 'bootstrap',
            'path'     => url('User/banks'),
        ]);
        $this->assign('count',count($row));
        $this->assign('row',$row);  
        return $this->fetch();
    }
    /**
     * [dowload_excel 会员导出]
     * @return [type] [description]
     */
    public function dowload_excel(){
        $path = dirname(__FILE__); //找到当前脚本所在路径
        $PHPExcel = new PHPExcel(); //实例化PHPExcel类，类似于在桌面上新建一个Excel表格
        $PHPSheet = $PHPExcel->getActiveSheet(); //获得当前活动sheet的操作对象
        $PHPSheet->setTitle('用户资料'); //给当前活动sheet设置名称
        $PHPSheet->setCellValue('A1','用户编号')
          ->setCellValue('B1','openid')
          ->setCellValue('C1','unionid')
          ->setCellValue('D1','用户昵称')
          ->setCellValue('E1','性别')
          ->setCellValue('F1','手机号')
          ->setCellValue('G1','真实姓名')
          ->setCellValue('H1','登录时间')
          ->setCellValue('I1','加入时间')
          ->setCellValue('J1','上级ID')
          ->setCellValue('K1','状态');
        $PHPSheet->getColumnDimension('A')->setWidth(20);
        $PHPSheet->getColumnDimension('B')->setWidth(20);
        $PHPSheet->getColumnDimension('D')->setWidth(15);
        $PHPSheet->getColumnDimension('E')->setWidth(20);
        $query = u_table::select();
        foreach($query as $k=>$v){
          $PHPSheet->setCellValue('A'.($k+2),$v['id'])
              ->setCellValue('B'.($k+2),$v['openid'])
              ->setCellValue('C'.($k+2),$v['unionid'])
              ->setCellValue('D'.($k+2),$v['nick_name'])
              ->setCellValue('E'.($k+2),$v['gender'])
              ->setCellValue('F'.($k+2),$v['mobile'])
              ->setCellValue('G'.($k+2),$v['true_name'])
              ->setCellValue('H'.($k+2),$v['login_time'])
              ->setCellValue('I'.($k+2),$v['create_time'])
              ->setCellValue('J'.($k+2),$v['parentid'])
              ->setCellValue('K'.($k+2),$v['static']);
        }
        $PHPWriter = PHPExcel_IOFactory::createWriter($PHPExcel,'Excel2007');//按照指定格式生成Excel文件，‘Excel2007’表示生成2007版本的xlsx，‘Excel5’表示生成2003版本Excel文件
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出07Excel文件
        //header('Content-Type:application/vnd.ms-excel');//告诉浏览器将要输出Excel03版本文件
        header('Content-Disposition: attachment;filename="01simple.xlsx"');//告诉浏览器输出浏览器名称
        header('Cache-Control: max-age=0');//禁止缓存
        $PHPWriter->save("php://output");
    }
    /**
     * [h_excel 汇款记录导出]
     * @return [type] [description]
     */
    public function h_excel(){
        $path = dirname(__FILE__); //找到当前脚本所在路径
        $PHPExcel = new PHPExcel(); //实例化PHPExcel类，类似于在桌面上新建一个Excel表格
        $PHPSheet = $PHPExcel->getActiveSheet(); //获得当前活动sheet的操作对象
        $PHPSheet->setTitle('汇款记录导出'); //给当前活动sheet设置名称
        $PHPSheet->setCellValue('A1','汇款编号')
          ->setCellValue('B1','提现表编号')
          ->setCellValue('C1','用户编号')
          ->setCellValue('D1','用户昵称')
          ->setCellValue('E1','机构名称')
          ->setCellValue('F1','申请金额')
          ->setCellValue('G1','汇款状态')
          ->setCellValue('H1','审核时间')
          ->setCellValue('I1','汇款时间')
          ->setCellValue('J1','备注');
        $PHPSheet->getColumnDimension('A')->setWidth(20);
        $PHPSheet->getColumnDimension('B')->setWidth(20);
        $PHPSheet->getColumnDimension('D')->setWidth(15);
        $PHPSheet->getColumnDimension('E')->setWidth(20);
        $PHPSheet->getColumnDimension('H')->setWidth(25);
        $PHPSheet->getColumnDimension('I')->setWidth(25);
        $query = Record::select();
        if ($this->request->param('static') == '1') {
            $query = Record::where('re_state',1)->select();
        }
        foreach($query as $k=>$v){
          $PHPSheet->setCellValue('A'.($k+2),$v['re_id'])
              ->setCellValue('B'.($k+2),$v['re_cid'])
              ->setCellValue('C'.($k+2),$v['re_uid'])
              ->setCellValue('D'.($k+2),$v['re_uname'])
              ->setCellValue('E'.($k+2),$v['re_company'])
              ->setCellValue('F'.($k+2),$v['re_cash']/100)
              ->setCellValue('G'.($k+2),$v['re_state'])
              ->setCellValue('H'.($k+2),$v['re_audit'])
              ->setCellValue('I'.($k+2),$v['re_cashtime'])
              ->setCellValue('J'.($k+2),$v['re_mark']);
        }
        $PHPWriter = PHPExcel_IOFactory::createWriter($PHPExcel,'Excel2007');//按照指定格式生成Excel文件，‘Excel2007’表示生成2007版本的xlsx，‘Excel5’表示生成2003版本Excel文件
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出07Excel文件
        //header('Content-Type:application/vnd.ms-excel');//告诉浏览器将要输出Excel03版本文件
        header('Content-Disposition: attachment;filename="01simple.xlsx"');//告诉浏览器输出浏览器名称
        header('Cache-Control: max-age=0');//禁止缓存
        $PHPWriter->save("php://output");
    }
}